const { Compilation } = require('webpack')
const { ConcatSource } = require("webpack-sources");
module.exports = class InsertBannerLog {
  constructor(options) {
    const {
      banner,
      style = 'color: #3366dd'
    } = options
    this.banner = banner
    this.style = style
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync('InsertBannerLog', (compilation, cb) => {
      const entryNames = Object.keys(compiler.options.entry)
      entryNames.forEach(entryName => {
        const files = compilation.entrypoints.get(entryName).getFiles()
        const entryFileName = files[0]
        // const entryAsset = compilation.getAsset(entryFileName)
        const chunk = compilation.chunks.find((chunk) => chunk.files.includes(entryFileName))
        const banner = compilation.getPath(this.banner, {
          filename: entryFileName,
          chunk
        })
        compilation.updateAsset(entryFileName, (oldSource) => {

          return new ConcatSource(oldSource, '\n', `console.log(\`%c${banner}\`, \`${this.style}\`)`)
        })
      })
      cb()
    })
  }
}